<template>
  <div id="normal-setting-components-box">
    <div class="flex-x box-12 bg-w">
      <div class="flex-1">
        <div class="font-16 font-w-600 border-btm">
          {{$t('common.base.rulerSet')}}
          <el-tooltip placement="top">
            <div slot="content">{{$t('product.setting.qrCodeSet.des1')}}</div>
            <i class="iconfont icon-warning-circle-fill" @click="toYuque" style="cursor:pointer;"></i>
          </el-tooltip>
        </div>
        <div class="font-w-600">{{$t('product.setting.qrCodeSet.title1')}}</div>
        <div class="two-sides common-item-tips">
          <span>{{$t('product.setting.qrCodeSet.des2')}}</span>
          <div>
            <el-switch v-model="qrcodeEnabled"
                       @change="saveFunc($event, 'qrcodeEnabled')"></el-switch>
            {{ qrcodeEnabled ? $t('common.base.enable') : $t('common.base.disable') }}
          </div>
        </div>
      </div>
    </div>

    <div class="flex-x box-12 bg-w" :class="!(qrcodeEnabled && qrCodeImportAndAutoRelationGray) ? 'mar-btm-10' : ''">
      <div class="flex-1">
        <div class="font-w-600 mar-top-20">{{$t('product.setting.qrCodeSet.title2')}}</div>
        <div class="two-sides common-item-tips">
          <span>{{$t('product.setting.qrCodeSet.des3')}}</span>
          <div>
            <el-switch v-model="hideDefaultLinkman"
                       @change="saveFunc($event, 'hideDefaultLinkman')"></el-switch>
            {{ hideDefaultLinkman ? $t('common.base.enable') : $t('common.base.disable') }}
          </div>
        </div>
      </div>
    </div>

    <!-- 允许用户导入生成二维码 -->
    <div class="flex-x box-12 bg-w" v-if="qrcodeEnabled && qrCodeImportAndAutoRelationGray">
      <div class="flex-1">
        <div class="font-w-600 mar-top-20">{{$t('product.setting.qrCodeSet.title7')}}</div>
        <div class="two-sides common-item-tips">
          <span>{{$t('product.setting.qrCodeSet.des11')}}</span>
          <div>
            <el-switch
              v-model="allowQrCodeImport"
              @change="qrCodeSetting($event, 'allowQrCodeImport')"
            ></el-switch>
            {{ allowQrCodeImport ? $t('common.base.enable') : $t('common.base.disable') }}
          </div>
        </div>
      </div>
    </div>

    <!-- 启用产品二维码与产品自动关联功能 -->
    <div class="flex-x box-12 bg-w mar-btm-10" v-if="qrcodeEnabled && qrCodeImportAndAutoRelationGray">
      <div class="flex-1">
        <div class="font-w-600 mar-top-20">{{$t('product.setting.qrCodeSet.title8')}}</div>
        <div class="two-sides common-item-tips mar-b-12">
          <span>{{$t('product.setting.qrCodeSet.des12')}}</span>
          <div>
            <el-switch 
              v-model="qrCodeAutoRelationEnable"
              @change="qrCodeSetting($event, 'qrCodeAutoRelationEnable')"
            ></el-switch>
            {{ qrCodeAutoRelationEnable ? $t('common.base.enable') : $t('common.base.disable') }}
          </div>
        </div>
        <div class="auto-bind-field-wrap" v-if="qrCodeAutoRelationEnable">
          <div class="auto-bind-field-content mar-b-5">
            <i18n path="product.setting.qrCodeSet.des13">
              <el-select
                class="mar-l-5 mar-r-5"
                place="data"
                v-model="qrCodeAutoRelationField" 
                clearable
                value-key="fieldName"
                :placeholder="$t('common.placeholder.select')"
              >
                <el-option
                  v-for="item in bindProductFields"
                  :key="item.fieldName"
                  :label="item.displayName"
                  :value="item">
                </el-option>
              </el-select>
            </i18n>
            <el-button
              type="primary"
              class="mar-l-16"
              @click="qrCodeSetting(qrCodeAutoRelationField, 'qrCodeAutoRelationField')"
              :disabled="pending"
            >{{ $t('common.base.save') }}</el-button>
          </div>
          <div class="auto-bind-tip-wrap">
            <p>{{ $t('common.base.toast') }}：</p>
            <p>{{ $t('product.setting.qrCodeSet.des14') }}</p>
            <p>{{ $t('product.setting.qrCodeSet.des15') }}</p>
          </div>
        </div>
      </div>
    </div>

    <!-- 产品小程序码设置 -->
    <div class="flex-x box-12 bg-w mar-btm-10" v-if="showMiniProgramSet">
      <div class="flex-1">
        <div class="font-w-600 mar-top-20">{{$t('product.setting.qrCodeSet.title3')}}</div>
        <div class="font-12 mar-top-5 two-sides">
          <span>{{$t('product.setting.qrCodeSet.des4')}}</span>
          <div>
            <el-switch v-model="appletQrcodeStatus"
                       @change="appletUpdateAttribute"></el-switch>
            {{ appletQrcodeStatus ? $t('common.base.enable') : $t('common.base.disable') }}
          </div>
        </div>
        <div class="font-12 mar-top-5">{{$t('product.setting.qrCodeSet.des5')}}</div>
      </div>
    </div>

    <div class="flex-x box-12 bg-w" v-if="qrcodeEnabled">
      <div class="flex-1">
        <div class="font-16 font-w-600 border-btm">{{$t('product.setting.qrCodeSet.title4')}}</div>
        <div class="font-w-600 mar-top-20">{{$t('product.setting.qrCodeSet.title5')}}</div>
        <div class="common-item-tips">{{$t('product.setting.qrCodeSet.des6')}}</div>
        <ul class="template-wrap">
          <li class="template-item">
            <div class="template-son template-blank" @click="showCreateDialog">
              <i class="iconfont icon-add2"></i>
              {{$t('common.base.createTemplate')}}
            </div>
            <p class="template-name">{{$t('common.base.createTemplate')}}</p>
          </li>
          <li class="template-item" v-for="item in templateList" :key="item.id">
            <div class="template-son template-default">
              <img style="height:auto;" :src="topImage">
              <tem-component
                v-for="data in item.list"
                :key="data.name"
                :data='data'
                :door-event-type='item.doorEventType'
                :show-fields='item.showFields'
                :all-event-list='allEventList'
                :paasList="item.doorPaasInfo"
              ></tem-component>
              <div class="template-son template-mark">
                <div class="mark-bg" v-if="item.catalogId" @click="deleteTemplate(item.id)">
                  <el-tooltip :content="$t('common.base.delete')" placement="top">
                    <i class="iconfont icon-qingkongshanchu" v-track="$track.formatParams('DELETE_QRCODE_TEMPLATE')"></i>
                  </el-tooltip>
                </div>
                <div class="mark-bg" @click="editTemplate(item)">
                  <el-tooltip :content="$t('common.base.edit')" placement="top">
                    <i class="iconfont icon-bianji1" v-track="$track.formatParams('EDIT_QRCODE_TEMPLATE')"></i>
                  </el-tooltip>
                </div>
              </div>
            </div>
            
            <p class="template-name">
              {{!item.catalogId ? $t('superQrcode.defaultTemplate') :item.productIntroduction}}
              <el-tooltip v-if="!item.catalogId" :content="$t('product.setting.qrCodeSet.des7')" placement="top">
                <i class="default-info iconfont icon-fdn-info"></i>
              </el-tooltip>
            </p>
            <div class="template-ass" v-if="item.catalogId">
              <span class="hasBind">{{$t('product.setting.qrCodeSet.des8')}}（{{item.associatedNum}}）</span>
              <el-button
                type="text"
                v-track="$track.formatParams('EDIT_ASSOCIATED_PRODUCT_TYPE')"
                @click="editAssociate(item.id)">
                {{$t('common.base.edit')}}
              </el-button>
            </div>
          </li>
        </ul>
      </div>
    </div>

    <div class="flex-x box-12 bg-w" v-if="qrcodeEnabled && !hideImRule">
      <div class="flex-1">
        <div class="font-w-600 mar-top-20">{{$t('product.setting.qrCodeSet.title6')}}</div>
        <div class="common-item-tips">{{$t('product.setting.qrCodeSet.des9')}}</div>
      </div>
      <el-button type="primary" @click="addRule">{{$t('common.base.createRuler')}}</el-button>
    </div>

    <div class="flex-x box-12 bg-w"
         v-if="qrcodeEnabled && !hideImRule">
      <el-table border
                stripe
                :data="list">
        <el-table-column prop="level"
                         width="100"
                         :label="$t('common.form.type.level')"></el-table-column>
        <el-table-column prop="ruleName"
                         :label="$t('common.base.rulerName')"></el-table-column>
        <el-table-column :label="$t('common.base.operation')">
          <template slot-scope="scope">
            <i class="iconfont icon-bianji pointer"
               @click="editRule(scope.row.id)"></i>
            <i class="iconfont icon-qingkongshanchu-copy pointer"
               @click="deleteRule(scope.row.id, scope.row.isSystem)"></i>
            <i class="iconfont icon-long-arrow-up pointer"
               @click="moveRule(scope.$index, 'top')"></i>
            <i class="iconfont icon-long-arrow-down pointer"
               @click="moveRule(scope.$index, 'down')"></i>
          </template>
        </el-table-column>
        <el-table-column :label="`${$t('common.base.enable')}/${$t('common.base.disable')}`">
          <template slot-scope="scope">
            <el-switch :disabled="scope.row.isSystem === 1"
                       @change="switchEnable($event, scope.row)"
                       v-model="scope.row.checked"></el-switch>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="flex-x box-12 bg-w" v-if="qrcodeEnabled && !hideImRule">
      <div class="warning">
        <i class="iconfont icon-fdn-info"></i>
        <div class="warning-txt">
          <h4>{{$t('common.base.haveAttention')}}</h4>
          <p>{{$t('product.setting.qrCodeSet.des10')}}</p>
          <el-form label-position="top" :model='lastForm' :inline='true' ref="lastForm" :rules='lastRules'>
            <el-form-item :label="$t('common.base.contactNumber')" prop='phone'>
              <el-input v-model="lastForm.phone" :placeholder="$t('common.placeholder.inputSomething', {data1:$t('common.base.contactNumber')})"></el-input>
            </el-form-item>
            <el-form-item :label="$t('common.base.weChatAccount')">
              <el-input v-model="lastForm.wxAccount" :placeholder="$t('common.placeholder.inputSomething', {data1:$t('common.base.weChatAccount')})"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="saveContact">{{$t('common.base.save')}}</el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </div>

    <el-dialog
      custom-class="ruleFormDialog"
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false">
      <el-form label-position="top" :model="form"
               :rules="rules"
               
               ref="form">
        <el-form-item :label="$t('product.setting.qrCodeSet.label1')"
                      prop="ruleName">
          <el-input type="text"
                    size="mini"
                    maxlength="10"
                    v-model="form.ruleName"
                    :placeholder="$t('product.setting.qrCodeSet.pla1', {data1:10})"></el-input>
        </el-form-item>
        <el-form-item :label="$t('product.setting.qrCodeSet.label2')"
                      required>
          <el-radio-group v-model="form.ruleType"
                          @change="ruleTypeChange">
            <el-radio :label="1">{{$t('product.setting.qrCodeSet.label7')}}</el-radio>
            <el-radio :label="2">{{$t('product.setting.qrCodeSet.label8')}}</el-radio>
            <el-radio :label="3">{{$t('product.setting.qrCodeSet.label9')}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item :label="$t('product.setting.qrCodeSet.label3')"
                      required
                      v-if="form.ruleType == 2">
          <div class="inline-block">
            <el-form-item>
              <el-select size="mini"
                         v-model="form.include"
                         :popper-append-to-body="false"
                         popper-class="select-popper">
                <el-option :label="$t('common.base.include')"
                           :value="1"></el-option>
                <el-option :label="$t('common.base.exclude')"
                           :value="0"></el-option>
              </el-select>
            </el-form-item>
          </div>
          <div class="inline-block ml-8">
            <el-form-item prop="address">
              <el-select size="mini"
                         multiple
                         collapse-tags
                         v-model="form.address"
                         :popper-append-to-body="false"
                         popper-class="select-popper">
                <el-option v-for="item in provinceList"
                           :key="item"
                           :label="item"
                           :value="item"></el-option>
              </el-select>
            </el-form-item>
          </div>
        </el-form-item>
        <el-form-item :label="$t('product.setting.qrCodeSet.label12')"
                      v-show="form.ruleType == 3"
                      required>
          <i18n path="product.setting.qrCodeSet.label13">
            <el-form-item place="module" class="selectConditions">
              <el-select @change="applyChange"     
                         v-model="form.apply"
                         size="mini"
                         :popper-append-to-body="false"
                         popper-class="select-popper">
                <el-option :label="$t('common.form.type.customer')"
                           :value="'customer'"></el-option>
                <el-option :label="$t('common.form.type.product')"
                           :value="'product'"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item place="displayName" prop="fieldName" class="fieldNameSelection">
              <el-select v-model="form.fieldName"
                         @change="fieldChange"
                         size="mini"
                         :popper-append-to-body="false"
                         popper-class="select-popper">
                <el-option v-for="item in fields"
                           :key="item.fieldName"
                           :label="item.displayName"
                           :value="item.fieldName"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item place="compareStr" class="compileSelection">
              <el-select v-model="form.equals"
                         size="mini"
                         :popper-append-to-body="false"
                         popper-class="select-popper">
                <el-option :label="$t('common.base.equal')"
                           :value="1"></el-option>
                <el-option :label="$t('common.base.notEqual')"
                           :value="0"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item place="productType" prop="option" class="productTypeSelection">
              <el-select v-if="form.apply==='product' && form.fieldName==='type'"
                         v-model="form.option"
                         size="mini"
                         :popper-append-to-body="false"
                         filterable
                         remote
                         :remote-method="queryCatalogsByPage"
                         :loading='loading'
                         popper-class="select-popper"
                         class="catalog-loadmore"
                         v-catalog-loadmore='catalogLoadmore'>
                <el-option v-for="item in catalogList"
                           :key="item.id"
                           :label='item.pathName'
                           :value='item.id'></el-option>
              </el-select>
              <el-select v-else
                         v-model="form.option"
                         size="mini"
                         :popper-append-to-body="false"
                         popper-class="select-popper">
                <el-option v-for="item in options"
                           :key="item"
                           :label="item"
                           :value="item"></el-option>
              </el-select>
            </el-form-item>
          </i18n>
        </el-form-item>
        <el-form-item :label="$t('product.setting.qrCodeSet.label5')"
                      required>
          <div class="inline-block">
            <el-form-item>
              <el-select size="mini"
                         @change="userTypeChange"
                         v-model="form.selectUserType"
                         :popper-append-to-body="false"
                         popper-class="select-popper">
                <el-option v-for="item in userTypes"
                           :key="item.value"
                           :label="item.label"
                           :value="item.value"></el-option>
              </el-select>
            </el-form-item>
          </div>
          <div class="inline-block ml-8" style="width: 172px;"
                  v-show="
                    form.selectUserType == 'user' ||
                      form.selectUserType == 'role' ||
                      form.selectUserType == 'tag' ||
                      form.selectUserType == 'tagLeader'
                  ">
            <el-form-item prop="selectUser"
                          v-if="form.selectUserType == 'role'">
              
              <!-- start 选择角色 -->
              <biz-role-select
                v-model="form.selectUser"
                :roles="userList"
                filterable 
                clearable
              >
              </biz-role-select>
              <!-- end 选择角色 -->
              
              <!-- <publink-select size="mini"
                              v-model="form.selectUser"
                              filterable
                              remote
                              clearable
                              :remote-method="getUserList"
                              :popper-append-to-body="false"
                              popper-class="select-popper"
                              :loading="loading"
                              class="select-loadmore"
                              v-el-select-loadmore='loadmore'>
                <el-option v-for="item in userList"
                              :key="item.userId || item.id"
                              :label="item.displayName || item.tagName || item.name"
                              :value="item.userId || item.id">
                  <template v-if="isOpenData && form.selectUserType == 'user'">
                    <open-data type="userName" :openid="item.staffId"></open-data>
                  </template> 
                </el-option>
                <template slot="multiple" slot-scope="{ item }">
                  <template v-if="isOpenData && form.selectUserType == 'user'">
                    <open-data type="userName" :openid="item.staffId"></open-data>
                  </template>
                  <template v-else>
                    {{item.displayName || item.tagName || item.name}}
                  </template>
                </template>
              </publink-select> -->
              
            </el-form-item>
            <el-form-item prop="selectUser" v-if="form.selectUserType == 'tag' || form.selectUserType == 'tagLeader'">
              <biz-team-select :value="team" @input="teamSelect"></biz-team-select>
            </el-form-item>
            <el-form-item prop="selectUsers"
                          v-if="form.selectUserType == 'user'">
                <!-- <base-select-user-input
                  multiple
                  v-model="form.selectUsers" 
                  @input="userChange"
                >
                </base-select-user-input> -->
              <publink-select size="mini"
                              class="select-loadmore"
                              v-model="form.selectUsers"
                              @change="userChange"
                              multiple
                              collapse-tags
                              filterable
                              remote
                              clearable
                              :remote-method="getUserList"
                              :popper-append-to-body="false"
                              popper-class="select-popper"
                              :loading="loading"
                              v-el-select-loadmore='loadmore'>
                <el-option v-for="item in userList"
                              :key="item.userId || item.id"
                              :label="item.displayName || item.tagName || item.name"
                              :origin="item"
                              :value="item.userId || item.id">
                  <template v-if="isOpenData && form.selectUserType == 'user'">
                    <open-data type="userName" :openid="item.staffId"></open-data>
                  </template>
                </el-option>
                <template slot="multiple" slot-scope="{ item }">
                  <template v-if="isOpenData && form.selectUserType == 'user'">
                    <open-data type="userName" :openid="item.staffId"></open-data>
                  </template>
                  <template v-else>
                    {{item.displayName || item.tagName || item.name}}
                  </template>
                </template>
              </publink-select>
            </el-form-item>
          </div>
        </el-form-item>
        <el-form-item :label="$t('product.setting.qrCodeSet.label6')"
                      required>
          <el-select v-model="form.distributePriority"
                     size="mini"
                     :popper-append-to-body="false"
                     popper-class="select-popper">
            <el-option :label="$t('product.setting.qrCodeSet.label11')"
                       :value="1"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer"
           class="dialog-footer">
        <el-button size="small"
                   @click="dialogVisible = false">{{$t('common.base.cancel')}}</el-button>
        <el-button size="small"
                   :disabled='pending'
                   type="primary"
                   @click="submitForm">{{$t('common.base.confirm')}}</el-button>
      </div>
    </el-dialog>

    <associate-dialog :tenant-id='tenantId' :catalog-view-auth='catalogViewAuth' @relation='relation' ref="associateDialog"></associate-dialog>
    <create-template :visiable.sync='createVisible' :last-form='lastForm' :tenant-id='tenantId' :template-list='templateList'></create-template>
  </div>
</template>

<script>
import { getRootWindowInitData } from '@src/util/window'
import { isOpenData, openAccurateTab } from '@src/util/platform';
import _ from 'lodash';
import { getRootWindow } from '@src/util/dom';
import {
  queryAllRules,
  removeDistributeRule,
  moveRule,
  modifyDistributeRule,
  saveFunc,
  qrCodeSetting,
  queryCSByCondition,
  addDistributeRule,
  queryApplyOptions,
  queryRuleInfo,
  productConfig,
  queryCatalogsByPage,
  modifyDistributeRuleState
} from '@src/api/ProductV2Api';
import { getProductFields } from '@src/api/ProductApi';
import {
  getAllSuperCodeTemplate,
  deleteTemplate,
  insertBaseSupercodeCustomerProvider,
  getBaseSupercodeCustomerProvider,
  queryEventType,
  getUserAuth
} from '@src/api/SuperQrcode';
import associateDialog from './components/associateDialog';
import createTemplate from './components/createTemplate';
import temComponent from './components/temComponent';
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'
import { validatePhone as validatePhone_ } from '@src/util/validator'
import { t } from '@src/locales'
const validatePhone = (rule, value, cb)=>{
  if(!value){
    cb();
  } else {
    if (validatePhone_(value, 3)) {
      cb()
    } else {
      cb(new Error(t('product.qrcodeSetting.lastDialog.text3')));
    }
  }
}
import {
  wechatGetAuthInfo,
  appletUpdateAttribute
} from '@src/api/DoMyself.js';

import { getLocalesOssUrl } from '@src/util/assets'
const topImage = getLocalesOssUrl('/topNav.png')
export default {
  name:'qrcode-set',
  data(){
    return {
      topImage,
      isOpenData,
      qrcodeEnabled:true,
      hideDefaultLinkman:true,
      allowQrCodeImport: false,
      qrCodeAutoRelationEnable: false,
      qrCodeAutoRelationField: '',
      bindProductFields: [],
      hideImRule: true, // 是否隐藏在线客服规则
      appletQrcodeStatus:false, // 微信小程序二维码设置
      pending: false,
      tenantId: '',
      userId: '',
      openType: 'add',
      dialogVisible: false,
      ruleId: null,
      form: {
        ruleName: '',
        ruleType: 1,
        selectUserType: 'user',
        selectUser: '',
        selectUsers: [],
        distributePriority: 1,
        include: 1,
        address: [],
        apply: 'customer',
        equals: 1,
        fieldName: '',
        displayName: '',
        option: '',
        level: '',
      },
      userParams: {},
      userKeywords: '',
      hasNextPage: true,
      catalogParams: {},
      catalogKeywords: '',
      catalogHasNextPage: true,
      fields: [],
      allOptions: [],
      options: [],
      list: [],
      catalogList: [],
      userList: [],
      // TODO-bdz 等待地址多语言
      // TODO 国际化待办 地址
      provinceList: [
        '北京市',
        '天津市',
        '上海市',
        '重庆市',
        '内蒙古自治区',
        '广西壮族自治区',
        '西藏自治区',
        '宁夏回族自治区',
        '新疆维吾尔自治区',
        '河北省',
        '山西省',
        '辽宁省',
        '吉林省',
        '黑龙江省',
        '江苏省',
        '浙江省',
        '安徽省',
        '福建省',
        '江西省',
        '山东省',
        '河南省',
        '湖北省',
        '湖南省',
        '广东省',
        '海南省',
        '四川省',
        '贵州省',
        '云南省',
        '陕西省',
        '甘肃省',
        '青海省',
        '香港特别行政区',
        '澳门特别行政区',
        '台湾省',
        '其他区域',
      ],
      loading: false,

      chosenUser: [],
      mulUsers: [],
      templateList:[],
      productIntroduction:'',
      copyTemplateId:null,
      createVisible:false,
      lastForm:{
        phone:null,
        wxAccount:null
      },
      lastRules:{
        phone:[
          {validator:validatePhone, trigger:'blur'}
        ]
      },
      team:[],
      allEventList:[],
      catalogViewAuth:false
    }
  },
  computed: {
    dialogTitle () {
      return this.openType == 'add' ? this.$t('product.setting.qrCodeSet.dialogTitle.title1') : this.$t('product.setting.qrCodeSet.dialogTitle.title2');
    },
    userTypes () {
      if (this.form.ruleType === 1) {
        return [
          { label: this.$t('product.setting.qrCodeSet.userTypes.label1'), value: 'user' },
          { label: this.$t('product.setting.qrCodeSet.userTypes.label2'), value: 'role' },
          { label: this.$t('product.setting.qrCodeSet.userTypes.label3'), value: 'tag' },
          { label: this.$t('product.setting.qrCodeSet.userTypes.label4'), value: 'tagLeader' },
        ];
      } else if (this.form.ruleType === 2) {
        return [
          { label: this.$t('product.setting.qrCodeSet.userTypes.label3'), value: 'tag' },
          { label: this.$t('product.setting.qrCodeSet.userTypes.label4'), value: 'tagLeader' },
          { label: this.$t('product.setting.qrCodeSet.userTypes.label5'), value: 'cusTag' },
          { label: this.$t('product.setting.qrCodeSet.userTypes.label6'), value: 'cusTagLeader' },
          { label: this.$t('product.setting.qrCodeSet.userTypes.label7'), value: 'customerManager' },
        ];
      }
      return [
        { label: this.$t('product.setting.qrCodeSet.userTypes.label1'), value: 'user' },
        { label: this.$t('product.setting.qrCodeSet.userTypes.label2'), value: 'role' },
        { label: this.$t('product.setting.qrCodeSet.userTypes.label3'), value: 'tag' },
        { label: this.$t('product.setting.qrCodeSet.userTypes.label4'), value: 'tagLeader' },
        { label: this.$t('product.setting.qrCodeSet.userTypes.label5'), value: 'cusTag' },
        { label: this.$t('product.setting.qrCodeSet.userTypes.label6'), value: 'cusTagLeader' },
        { label: this.$t('product.setting.qrCodeSet.userTypes.label7'), value: 'customerManager' },
      ];

    },
    rules () {
      let rule = {
        ruleName: [
          { required: true, message: this.$t('product.setting.qrCodeSet.rulers.des1'), trigger: 'blur' },
        ],
      };
      const msg1 = this.$t('common.placeholder.select');
      if (this.form.ruleType == 1) {
        if (this.form.selectUserType == 'user') {
          rule.selectUsers = [
            {
              type: 'array',
              required: true,
              message: msg1,
              trigger: ['blur', 'change'],
            },
          ];
        } else {
          rule.selectUser = [
            { required: true, message: msg1, trigger: ['blur', 'change'] },
          ];
        }
      } else if (this.form.ruleType == 2) {
        rule.address = [
          {
            type: 'array',
            required: true,
            message: msg1,
            trigger: ['blur', 'change'],
          },
        ];
        if (
          this.form.selectUserType == 'role'
          || this.form.selectUserType == 'tag'
          || this.form.selectUserType == 'tagLeader'
        ) {
          rule.selectUser = [
            { required: true, message: msg1, trigger: ['blur', 'change'] },
          ];
        }
      } else {
        rule.fieldName = [
          { required: true, message: msg1, trigger: ['blur', 'change'] },
        ];
        rule.option = [
          { required: true, message: msg1, trigger: ['blur', 'change'] },
        ];
        if (this.form.selectUserType == 'user') {
          rule.selectUsers = [
            {
              type: 'array',
              required: true,
              message: msg1,
              trigger: ['blur', 'change'],
            },
          ];
        } else if (
          this.form.selectUserType == 'role'
          || this.form.selectUserType == 'tag'
          || this.form.selectUserType == 'tagLeader'
        ) {
          rule.selectUser = [
            { required: true, message: msg1, trigger: ['blur', 'change'] },
          ];
        }
      }
      return rule;
    },
    tenantType(){
      return getRootWindowInitData()?.tenantType
    },
    // 二维码导入和自动关联灰度
    qrCodeImportAndAutoRelationGray() {
      const RootWindow = getRootWindow(window)
      return RootWindow.grayAuth?.qrCodeImportAndAutoRelation || false
    },
    showMiniProgramSet(){
      const RootWindow = getRootWindow(window);
      return RootWindow.grayAuth?.appletsService
    },
  },
  created(){
    const rootWindow = getRootWindow(window);
    const user = JSON.parse(rootWindow._init).user;
    this.tenantId = user.tenantId;
    window.sessionStorage.setItem('qrcode_set_tenantId', this.tenantId);
    this.userId = user.userId;
    this.userParams = {
      tenantId: this.tenantId,
      pageSize: 10,
      pageNum: 1,
      searchType: '',
      keywords: ''
    }
    this.catalogParams = {
      tenantId: this.tenantId,
      pageNum: 1,
      pageSize: 10,
      keyWord: ''
    }
  },
  mounted(){
    this.queryEventType();
    this.productConfig();
    this.getBindProductFields();
    this.getAllSuperCodeTemplate();
    this.getBaseSupercodeCustomerProvider();
    this.getUserAuth();
    this.wechatGetAuthInfo()
  },
  methods:{
    // 获取权限，是否可点击产品跳转
    async getUserAuth(){
      let {code, result, message} = await getUserAuth();
      if(code === 0){
        this.catalogViewAuth = result.PRODUCT_CATALOG_VIEW && result.PRODUCT_CATALOG_VIEW === 3;
      }else{
        this.$notify.error({
          title: this.$t('common.base.toast'),
          message,
          duration: 2000,
        });
      }
    },
    // 获取所有事件
    async queryEventType(){
      try{
        const params = {
          tenantId:this.tenantId,
          id:''
        }
        const {data, code, msg} = await queryEventType(params);
        if(code === '200'){
          this.allEventList = data;
        }else{
          this.$notify.error({
            title: this.$t('common.base.toast'),
            message: msg,
            duration: 2000,
          });
        }
      }catch(err){
        console.error(err);
      }
    },
    // 选择部门/部门主管
    teamSelect(val){
      this.team = val;
      if(val.length) this.form.selectUser = val[0].id;
      else this.form.selectUser = '';
      this.$refs.form.validateField('selectUser')
    },
    // 打开语雀
    toYuque(){
      let url = ''
      if(this.tenantType == 2) {
        url = 'https://docs.qq.com/doc/p/d36484998ea402d98d59c3eeda6aad8e97e9cd15?dver=2.1.27237808'
      } else if(this.tenantType == 4) {
        url = 'https://publink-hz.feishu.cn/wiki/wikcnmXbF9yZn67aYOaZ5mRF6fg'
      } else {
        url = 'https://doc.shb.ltd/shb_xoqazk/ia4qctp2ly559d1m/wtr4x2a43al72qae/st8453y62ancq9ki.html'
      }
      window.open(url, '_blank');
    },
    // 关联或取消关联回调
    relation(){
      this.getAllSuperCodeTemplate();
    },
    // 查询产品二维码客服的兜底规则联系人员
    async getBaseSupercodeCustomerProvider(){
      try{
        let {code, data, msg} = await getBaseSupercodeCustomerProvider({tenantId:this.tenantId});
        if(code === '200'){
          if(data){
            this.lastForm.phone = data.phone;
            this.lastForm.wxAccount = data.wxAccount;
          }
        }else{
          this.$platform.notification({
            type: 'error',
            title: this.$t('common.base.toast'),
            message: msg
          })
        }
      }catch(err){
        console.error(err);
      }
    },
    // 编辑关联产品类型
    editAssociate(id){
      window.sessionStorage.setItem('qrcode_associate_templateId', id);
      this.$refs.associateDialog.open();
    },
    // 保存手机号、微信号
    saveContact(){
      this.$refs.lastForm.validate((valid) => {
        if(valid){
          try{
            const params = {
              tenantId:this.tenantId,
              phone:this.lastForm.phone,
              wxAccount:this.lastForm.wxAccount
            }
            insertBaseSupercodeCustomerProvider(params).then(res=>{
              const code = res.code;
              const msg = res.msg;
              if(code === '200'){
                this.$platform.notification({
                  type: 'success',
                  title: this.$t('common.base.toast'),
                  message: this.$t('common.base.tip.saveSuccess')
                })
              }else{
                this.$platform.notification({
                  type: 'error',
                  title: this.$t('common.base.toast'),
                  message: msg
                })
              }
            });
          }catch(err){
            console.error(err);
          }
        }
      });
    },
    // 删除模版
    deleteTemplate(templateId){
      this.$confirm(this.$t('product.setting.qrCodeSet.deleteTemplate.tips1'), this.$t('common.base.toast'), {
        confirmButtonText: this.$t('common.base.confirm'),
        cancelButtonText: this.$t('common.base.cancel'),
        type: 'warning'
      }).then(()=>{
        deleteTemplate({templateId, tenantId:this.tenantId}).then(res=>{
          if(res.code === '200'){
            this.$platform.notification({
              type: 'success',
              title: this.$t('common.base.toast'),
              message: this.$t('common.base.tip.deleteSuccess')
            })
            this.getAllSuperCodeTemplate();
          }else{
            this.$platform.notification({
              type: 'error',
              title: this.$t('common.base.toast'),
              message: res.msg
            })
          }
        })
      }).catch(()=>{});
    },
    // 编辑模版
    editTemplate(item){
      const params = {
        id:item.id,
        catalogId:item.catalogId,
        doorEventType:item.doorEventType || [],
        showFields:item.showFields || [],
        setting:item.setting || {},
        productIntroduction:item.productIntroduction,
        lastForm:this.lastForm
      }
      window.sessionStorage.setItem('edit_qrcode_template_params', JSON.stringify(params));
      // this.$platform.openTab({
      //   id: 'superqrcodeSet',
      //   title: '产品二维码配置',
      //   close: true,
      //   url: '/setting/superQrcode',
      //   reload:true
      // });
      openAccurateTab({
        type: PageRoutesTypeEnum.PageSettingSuperQrcode,
        reload:true
      })
      let id = window.frameElement && window.frameElement.dataset.id;
      this.$platform.closeTab(id);
    },
    // 查询租户下的产品二维码模版
    async getAllSuperCodeTemplate(){
      try{
        const params = {

          tenantId:this.tenantId,
          userId:this.userId
        }
        let {code, data} = await getAllSuperCodeTemplate(params);
        if(code === '200'){
          const arr = [
            'productPicture',
            'productIntroduction',
            'selfService',
            'productInformation',
            'productVideo',
            'productInstructions',
            'onlineService',
            'images',
            'companyInfo',
          ];
          console.log(data)
          data.forEach(item=>{
            let list = [];
            const s = item.setting;
            for(let k in s){
              if(s[k].isOpen && arr.find(a=>a === k)){
                list.push({
                  name:k,
                  ...s[k]
                });
              }
            }
            item.list = list.sort((a, b)=>a.order - b.order);
          });
          this.templateList = data;
        }else{
          this.$platform.notification({
            type: 'error',
            title: this.$t('common.base.toast'),
            message: data
          })
        }
      }catch(err){
        console.error(err);
      }
    },
    // 新建模版
    showCreateDialog(){
      this.createVisible = true;
      // window.sessionStorage.setItem('edit_qrcode_template_params',JSON.stringify({templateId:0}));
      // this.$platform.openTab({
      //   id: 'superqrcodeSet',
      //   title: '产品二维码配置',
      //   close: true,
      //   url: '/setting/superQrcode'
      // });
      // let id = window.frameElement && window.frameElement.dataset.id;
      // this.$platform.closeTab(id);
    },
    catalogLoadmore () {
      if (this.catalogHasNextPage) this.queryCatalogsByPage('', false);
    },
    loadmore () {
      if (this.hasNextPage) this.getUserList(null, false);
    },
    // 获取开关状态
    async productConfig () {
      let res = await productConfig();
      if (res.status === 0) {
        this.productSearchOnMobile = res.data.productConfig.productSearchOnMobile;
        this.qrcodeEnabled = res.data.productConfig.qrcodeEnabled;
        this.hideDefaultLinkman = res.data.productConfig.hideDefaultLinkman;
        this.allowQrCodeImport = res.data.allowQrCodeImport === 'true' ? true : false;
        this.qrCodeAutoRelationEnable = res.data.qrCodeAutoRelationEnable === 'true' ? true : false;
        try {
          this.qrCodeAutoRelationField = res.data.qrCodeAutoRelationField ? JSON.parse(res.data.qrCodeAutoRelationField) : '';
        } catch(err) {
          console.error('qrCodeAutoRelationField data error:', err);
        }
        this.hideImRule = res.data.productConfig.hideImRule;
        if (this.qrcodeEnabled) {
          this.queryAllRules();
        }
      } else {
        this.$platform.alert(res.message);
      }
    },
    // 获取字段
    async getFields () {
      const params = {
        tenantId: this.tenantId,
        applyType: this.form.apply
      }
      let res = await queryApplyOptions(params);
      if (res.code === '200') {
        this.allOptions = res.data;
        this.fields = this.allOptions.map(item => {
          return {
            fieldName: item.fieldName,
            displayName: item.displayName
          }
        });
        if (this.form.fieldName) {
          this.options = this.allOptions.find(item => item.fieldName == this.form.fieldName).setting.dataSource;
        }
      } else {
        this.$platform.alert(res.msg);
      }
    },
    // 改变客服人员类型
    userTypeChange (val) {
      this.team = []
      this.form.selectUsers = [];
      this.form.selectUser = '';
      this.userList = [];
      this.keywords = '';
      if (val === 'user' || val === 'role' || val === 'tag' || val === 'tagLeader') this.getUserList();
    },
    // 改变规则类型
    ruleTypeChange (val) {
      this.form.selectUsers = [];
      this.form.selectUser = '';
      this.team = [];
      if (val == 1 || val == 3) {
        this.form.selectUserType = 'user';
      } else {
        this.form.selectUserType = 'tag';
      }
      this.$nextTick(() => {
        this.$refs.form.clearValidate();
      })
      this.getUserList();
    },
    // 改变应用条件
    applyChange (val) {
      this.form.fieldName = '';
      this.form.option = '';
      this.getFields();
    },
    // 改变字段
    fieldChange (val) {
      this.form.option = '';
      this.options = this.allOptions.find(item => item.fieldName == val).setting.dataSource;
      if (val === 'type' && this.form.apply === 'product') {
        this.queryCatalogsByPage();
      }
    },
    // 获取产品类型字段
    queryCatalogsByPage: _.debounce(function (keyWord = '', refresh = true) {
      if (keyWord) {
        this.catalogKeywords = keyWord;
      }
      if (refresh) {
        this.catalogParams.pageNum = 1;
      } else {
        this.catalogParams.pageNum++;
      }
      this.catalogParams.keyWord = this.catalogKeywords;
      this.loading = true;
      queryCatalogsByPage(this.catalogParams).then(res => {
        this.loading = false;
        if (res.code === '200') {
          this.catalogHasNextPage = res.data.hasNextPage;
          if (refresh) this.catalogList = res.data.list;
          else this.catalogList.push(...res.data.list);
        } else {
          this.$platform.alert(res.msg);
        }
      })
    }, 300),
    // 保存
    submitForm () {
      this.$refs.form.validate((valid) => {
        if (valid) {
          let params = this.buildParams();
          if (this.openType == 'add') {
            this.addDistributeRule(params);
          } else {
            this.modifyDistributeRule(params);
          }
        }
      });
    },
    // 新建保存
    async addDistributeRule (params) {
      this.pending = true;
      let res = await addDistributeRule(params);
      this.pending = false;
      if (res.code == 200) {
        this.dialogVisible = false;
        this.queryAllRules();
        this.$message({
          message: res.data || this.$t('common.base.tip.createSuccess'),
          type: 'success'
        })
      } else {
        this.$platform.alert(res.msg)
      }
    },
    // 编辑保存
    async modifyDistributeRule (params) {
      this.pending = true;
      let res = await modifyDistributeRule(params);
      this.pending = false;
      if (res.code == 200) {
        this.dialogVisible = false;
        this.queryAllRules();
        this.$message({
          message: res.data || this.$t('common.base.tip.edit2Success'),
          type: 'success'
        })
      } else {
        this.$platform.alert(res.msg)
      }
    },
    // 构建保存的参数
    buildParams () {
      let params = {
        tenantId: this.tenantId,
        ruleName: this.form.ruleName,
        ruleType: this.form.ruleType,
        distributePriority: this.form.distributePriority,
        enabled: 1,
        level: this.form.level,
        isSystem: this.form.isSystem || 0,
      };
      if (this.openType == 'add') {
        params.createUser = this.userId;
      } else {
        params.id = this.ruleId;
        params.updateUser = this.userId;
      }
      if (this.form.ruleType == 1) {
        if (this.form.selectUserType == 'user') {
          params.distributeCondition = { group: 'user' };
          params.candidate = { info: [] };
          this.form.selectUsers.forEach((userId) => {
            const item = this.mulUsers.find((u) => u.userId == userId);
            params.candidate.info.push({
              userId,
              userName: item.displayName,
              times: 0,
            });
          });
        } else if(this.form.selectUserType == 'tag' || this.form.selectUserType == 'tagLeader'){
          params.distributeCondition = {
            group: this.form.selectUserType,
            groupId: this.form.selectUser,
            groupName: this.team[0].tagName,
          };
          params.candidate = null;
        } else {
          const item = this.userList.find((u) => u.id == this.form.selectUser);
          params.distributeCondition = {
            group: this.form.selectUserType,
            groupId: this.form.selectUser,
            groupName: item.name || item.tagName,
          };
          params.candidate = null;
        }
      } else if (this.form.ruleType == 2) {
        params.candidate = null;
        params.distributeCondition = {
          group: this.form.selectUserType,
          include: this.form.include,
          address: this.form.address,
        };
        if (
          this.form.selectUserType == 'tag'
          || this.form.selectUserType == 'tagLeader'
        ) {
          var item = this.userList.find((u) => u.id == this.form.selectUser);
          params.distributeCondition.groupId = this.form.selectUser;
          params.distributeCondition.groupName = this.team[0].tagName;
        }
      } else {
        const fieldItem = this.fields.find(
          (item) => item.fieldName == this.form.fieldName
        );
        params.distributeCondition = {
          group: this.form.selectUserType,
          apply: this.form.apply,
          fieldName: this.form.fieldName,
          equals: this.form.equals,
          option: this.form.option,
          displayName: fieldItem.displayName,
        };
        params.candidate = null;
        if (this.form.selectUserType == 'user') {
          params.candidate = { info: [] };
          this.form.selectUsers.forEach((userId) => {
            const item = this.userList.find((u) => u.userId == userId);
            params.candidate.info.push({
              userId,
              userName: item.displayName,
              times: 0,
            });
          });
        } else if (
          this.form.selectUserType == 'role'
        ) {
          var item = this.userList.find((u) => u.id == this.form.selectUser);
          params.distributeCondition.groupId = item.id;
          params.distributeCondition.groupName = item.tagName || item.name;
        } else if(this.form.selectUserType == 'tag' || this.form.selectUserType == 'tagLeader'){
          params.distributeCondition.groupId = this.form.selectUser;
          params.distributeCondition.groupName = this.team[0].tagName;
        }
      }
      return params;
    },
    // 新建打开窗口
    addRule () {
      this.getUserList('');
      this.dialogVisible = true;
      this.openType = 'add';
      this.form = {
        ruleName: '',
        ruleType: 1,
        selectUserType: 'user',
        selectUser: '',
        selectUsers: [],
        distributePriority: 1,
        include: 1,
        address: [],
        apply: 'customer',
        equals: 1,
        fieldName: '',
        option: '',
        level: '',
      };
      this.getFields();
    },
    // 获取指定人员
    getUserList: _.debounce(function (keywords = '', refresh = true, first = false) {
      this.loading = true;
      if (keywords) {
        this.userKeywords = keywords;
      }
      if (refresh) {
        this.userParams.pageNum = 1;
      } else {
        this.userParams.pageNum++;
      }
      this.userParams.searchType = this.form.selectUserType;
      this.userParams.keywords = this.userKeywords;
      queryCSByCondition(this.userParams).then(res => {
        this.loading = false;
        if (res.code === '200') {
          this.hasNextPage = res.data.hasNextPage;
          if (res.data && res.data.list) {
            if (refresh) this.userList = res.data.list;
            else this.userList.push(...res.data.list);

            if (first) {
              if (this.form.selectUserType === 'user') {
                this.chosenUser.forEach(item => {
                  const exist = this.userList.find(user => user.userId === item.userId);
                  if (!exist) this.userList.unshift(item);
                });
              } else {
                const exist = this.userList.find(item => item.id === this.chosenUser[0].id);
                if (!exist) this.userList.unshift(this.chosenUser[0]);
              }
            }
          }
        } else {
          this.$platform.alert(res.msg);
        }
      })
    }, 300),
    // 启用/禁用 功能设置
    async saveFunc (state, flow) {
      const params = {
        state,
        flow,
      };
      let res = await saveFunc(params);
      if (res.status === 0) {
        if (flow === 'qrcodeEnabled') {
          let fromId = window.frameElement.getAttribute("fromid") || ''
          // 指定刷新二维码列表页
          fromId = fromId.includes('M_PRODUCT_QR_CODE') ? fromId : 'frame_tab_M_PRODUCT_QR_CODE'
          this.$platform.refreshTab(fromId)
        }
        if (flow === 'qrcodeEnabled' && state && this.list.length === 0) {
          this.queryAllRules();
        }
      } else {
        this.$platform.alert(res.message);
      }
    },
    // 修改二维码配置
    async qrCodeSetting (value, key) {
      if (key == 'allowQrCodeImport' || key == 'qrCodeAutoRelationEnable') {
        value = String(value)
      } else if (key == 'qrCodeAutoRelationField') {
        value = value ? JSON.stringify({
          fieldName: value.fieldName,
          formType: value.formType,
          isSystem: value.isSystem,
        }) : ''
      }
      const params = {
        fieldSettingKey: key,
        fieldSettingValue: value,
      };
      this.pending = true;
      let res = await qrCodeSetting(params);
      this.pending = false;
      if (res.success && key == 'qrCodeAutoRelationField') {
        this.$platform.notification({
          type: 'success',
          title: this.$t('common.base.toast'),
          message: this.$t('common.base.tip.saveSuccess')
        })
      }
      if (!res.success) {
        this.$platform.alert(res.msg);
      }
    },
    // 启用/禁用 规则
    async switchEnable (enabled, row) {
      const params = {
        id: row.id,
        enabled: enabled ? 1 : 0,
      };
      let res = await modifyDistributeRuleState(params);
      if (res.code !== '200') {
        this.$platform.alert(res.msg);
      }
    },
    // 规则移动
    async moveRule (index, direction) {
      if (index === 0 && direction === 'top') {
        return;
      }
      if (index === this.list.length - 1 && direction === 'down') {
        return;
      }
      let arr = this.list.map((item) => {
        return {
          id: item.id,
        };
      });
      let moveItem = arr.splice(index, 1);
      if (direction === 'top') {
        arr.splice(index - 1, 0, moveItem[0]);
      } else {
        arr.splice(index + 1, 0, moveItem[0]);
      }
      arr.forEach((item, index) => {
        item.level = index + 1;
      });
      let res = await moveRule(arr);
      if (res.code === '200') {
        this.queryAllRules();
      } else {
        this.$platform.alert(res.msg);
      }
    },
    // 删除规则
    deleteRule (id, isSystem) {
      if (isSystem) {
        return this.$platform.alert(this.$t('product.setting.qrCodeSet.deleteRule.tips1'));
      }
      this.$confirm(this.$t('common.base.tip.confirmForDelete'), this.$t('common.base.toast'), {
        confirmButtonText: this.$t('common.base.confirm'),
        cancelButtonText: this.$t('common.base.cancel'),
        type: 'warning',
      })
        .then(() => {
          const params = {
            id,
            tenantId: this.tenantId,
          };
          removeDistributeRule(params).then((res) => {
            if (res.code === '200') {
              this.queryAllRules();
            } else {
              this.$platform.alert(res.msg);
            }
          });
        })
        .catch(() => { });
    },
    // 编辑规则
    async editRule (id) {
      let res = await queryRuleInfo({ id });
      if (res.code === '200') {
        let form = this.form;
        this.openType = 'edit';
        const result = res.data;
        this.ruleId = result.id;
        form.ruleName = result.ruleName;
        form.ruleType = result.ruleType;
        form.selectUserType = result.distributeCondition.group;
        form.distributePriority = result.distributePriority;
        form.level = result.level;
        form.isSystem = result.isSystem;
        if (form.selectUserType == 'user') {
          this.chosenUser = result.candidate.info;
          this.chosenUser.forEach(item => {
            item.displayName = item.userName;
          });
          this.mulUsers = this.chosenUser.map(item => {
            return {
              userId: item.userId,
              displayName: item.displayName
            }
          });
          this.getUserList(null, true, true);
          
          form.selectUsers = result.candidate.info.map(item => item.userId);
          
        } else if (form.selectUserType == 'role') {
          this.chosenUser = [result.distributeCondition];
          this.chosenUser.forEach(item => {
            item.id = item.groupId;
            if (form.selectUserType == 'role') {
              item.name = item.groupName;
            } else {
              item.tagName = item.groupName;
            }
          });
          form.selectUser = result.distributeCondition.groupId;
          this.getUserList(null, true, true);
        }else if(form.selectUserType == 'tag' || form.selectUserType == 'tagLeader'){
          this.team = [{
            id:result.distributeCondition.groupId,
            tagName:result.distributeCondition.groupName
          }]
        }
        form.address = result.distributeCondition.address || [];
        form.include = isNaN(result.distributeCondition.include) ? 1 : result.distributeCondition.include;
        form.apply = result.distributeCondition.apply || 'customer';
        form.fieldName = result.distributeCondition.fieldName || '';
        form.equals = isNaN(result.distributeCondition.equals) ? 1 : result.distributeCondition.equals;
        form.option = result.distributeCondition.option || '';
        if (form.apply === 'product' && form.fieldName === 'type') {
          this.catalogList = [{
            id: form.option,
            pathName: result.distributeCondition.pathName
          }];
        }

        this.getFields();
        this.dialogVisible = true;
      } else {
        this.$platform.alert(res.msg);
      }
    },
    // 人员列表选择
    userChange (val) {
      let arr = [];
      val.forEach(userId => {
        const nowExist = this.userList.find(item => item.userId === userId);
        if (nowExist) {
          arr.push({
            userId: nowExist.userId,
            displayName: nowExist.displayName
          });
        } else {
          const oldExist = this.mulUsers.find(item => item.userId === userId);
          if (oldExist) {
            arr.push({
              userId: oldExist.userId,
              displayName: oldExist.displayName
            });
          }
        }
      });
      this.mulUsers = arr;
    },
    // 获取所有规则
    async queryAllRules () {
      if (this.hideImRule) return
      const params = {
        tenantId: this.tenantId,
      };
      let res = await queryAllRules(params);
      if (res.code === '200') {
        res.data.forEach((item) => {
          item.checked = item.enabled === 1;
        });
        this.list = res.data;
      } else {
        this.$platform.alert(res.msg);
      }
    },
    // 获取绑定产品的字段
    getBindProductFields() {
      if (!this.qrCodeImportAndAutoRelationGray) return;
      getProductFields({ isFromSetting: true }).then(res => {
        // 支持产品编号、单行文本和数字
        this.bindProductFields = (res.data || []).filter(f => f.fieldName == 'serialNumber' || ['text', 'number'].includes(f.formType))
      })
    },
    // 获取授权信息-小程序
    async wechatGetAuthInfo(){
      const {data} = await wechatGetAuthInfo()
      if(data.status == 1){
        this.appletQrcodeStatus = !!data.data.attribute.appletQrcodeStatus
      }
      return data.status
    },
    async appletUpdateAttribute(){
      const params = {
        appletQrcodeStatus:this.appletQrcodeStatus
      }
      const {success, message} = await appletUpdateAttribute(params)
      if(!success){
        this.$message.error(message)
        this.appletQrcodeStatus = !this.appletQrcodeStatus
      }
    }
  },
  components:{
    [associateDialog.name]:associateDialog,
    [createTemplate.name]:createTemplate,
    [temComponent.name]:temComponent
  },
  directives: {
    'el-select-loadmore': {
      bind (el, binding) {
        const SELECT_DOM = el.querySelector('.select-loadmore .el-select-dropdown__wrap');
        SELECT_DOM.addEventListener('scroll', () => {
          const condition = SELECT_DOM.scrollHeight - SELECT_DOM.scrollTop <= SELECT_DOM.clientHeight;
          if (condition) {
            binding.value();
          }
        })
      }
    },
    'catalog-loadmore': {
      bind (el, binding) {
        const SELECT_DOM = el.querySelector('.catalog-loadmore .el-select-dropdown__wrap');
        SELECT_DOM.addEventListener('scroll', () => {
          const condition = SELECT_DOM.scrollHeight - SELECT_DOM.scrollTop <= SELECT_DOM.clientHeight;
          if (condition) {
            binding.value();
          }
        })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.el-radio {
  margin-right: 10px;
}
::v-deep .el-radio__label {
  padding-left: 5px;
}
.two-sides{
  display: flex;
  justify-content: space-between;
}
.pointer {
  cursor: pointer;
}
.mar-btm-10 {
  margin-bottom: 10px;
}
.border-btm {
  padding-bottom: 8px;
  margin-bottom: 10px;
  border-bottom: 1px solid #eee;
}
.mar-top-52 {
  margin-top: 52px;
}
.mar-top-5 {
  margin-top: 5px;
}
.select-popper {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.template-wrap{
  background: $bg-color-l2;
  padding: 20px;
  display: flex;
  flex-wrap: wrap;
  margin-top: 10px;

  .template-item{
    margin-right: 20px;
    width: 200px;
    height: 420px;
    cursor: pointer;
    position: relative;

    .template-name{
      margin-top: 10px;
      margin-bottom: 0;
      color:$text-color-primary;
    }
    .template-ass{
      display: flex;
      justify-content: space-between;
      margin-top: 5px;

      ::v-deep .el-button{
        padding: 0;
        font-size: 12px;
      }
      .hasBind{
        font-size: 12px;
        color: $text-color-secondary;
      }
    }

    .template-son{
      height: 340px;
    }
    .template-default{
      overflow: hidden;
      position: relative;
      border: 1px solid #d9d9d9;
      border-radius: 4px;
      &:hover{
        .template-mark{
           display:flex;
        }
      }
    }

    .template-blank{
      border: 1px dashed $color-border-l1;
      background-color: #fff;
      font-size: 16px;
      color:$text-color-gray;
      text-align: center;

      i{
        font-size: 30px;
        display: block;
        margin-top: 120px;
      }
    }
    .default-info{
      color: $text-color-secondary;
    }
    .template-mark{
      position: absolute;
      width: 200px;
      top: 0;
      background-color: #00000066;
      display: none;
      align-items: center;
      justify-content: space-around;
      padding: 0 20px;
      .mark-bg{
        width: 30px;
        height: 30px;
        border-radius: 50%;
        background-color: #00000033;
        color: #fff;
        text-align: center;
        line-height: 30px;
      }
    }
  }
}
.warning{
  background-color: #fffbe6;
  border: 1px solid #ffe58f;
  border-radius: 2px;
  color: $text-color-regular;
  padding: 12px;
  display: flex;
  width: 100%;

  i{
    color: #ffe58f;
    font-size: 24px;
    margin-right: 10px;
    transform: translateX(-6px);
  }

  .warning-input{
    width: 160px;
  }
}

.auto-bind-field-wrap {
  padding: 8px 12px;
  background: #F5F8FA;
  color: #8C8C8C;
  .auto-bind-field-content {
    color: #262626;
  }
  p {
    margin: 0;
    line-height: 22px;
  }
  .mar-l-16 {
    margin-left: 16px;
  }
}

.common-item {
  &-label {
    line-height: 14px;
  }
  &-tips {
    font-size: 14px;
    color: #8C8C8C;
    line-height: 14px;
    margin-top: 12px;
  }
}

.selectConditions {
  width: 16%;
  display: inline-block;
  text-align: center;
  padding: 0 4px 0 4px;
}
.fieldNameSelection {
  display: inline-block;
  text-align: center;
  width: 25%;
  padding: 0 4px 0 8px;
}
.compileSelection {
  display: inline-block;
  text-align: center;
  width: 16%;
  padding: 0 4px 0 4px;
}
.productTypeSelection {
  display: inline-block;
  text-align: center;
  width: 25%;
  padding: 0 8px 0 4px;
}

.ml-8 {
  margin-left: 8px;
}

.inline-block {
  display: inline-block;
}

.text-center {
  text-align: center;
}

</style>

<style lang="scss">
.base-select-user-input {
  .el-input__inner {
    height: 28px !important;
  }
}
.ruleFormDialog {
  min-width: 580px;
}
</style>